from fastapi import APIRouter, Query, Depends
from pydantic import UUID4

from .filters import MessageFilter
from .models import Message, BrowserChoice, SystemChoice
from .schemas import MessageOutSchema, MessageEditSchema, MessageFilterSchema
from base.base_schemas import BaseSelectOptionSchema
from fastapi_pagination import Page
from fastapi_pagination.ext.tortoise import paginate
from typing import Annotated
from utils.deps import get_client_info
from utils.auth import public_route

router = APIRouter()


@router.get("", response_model=Page[MessageOutSchema])
async def get_message_list(
    query_filter: Annotated[MessageFilterSchema, Query()]
) -> Page[MessageOutSchema]:
    query = Message.all()
    query = MessageFilter.filter(query, query_filter)
    return await paginate(query)


@router.get("/public", response_model=Page[MessageOutSchema])
@public_route()
async def get_public_message_list() -> Page[MessageOutSchema]:
    query = Message.filter(active=True).order_by("-created_at")
    return await paginate(query)


@router.get("/public/top", response_model=list[MessageOutSchema])
@public_route()
async def get_public_top_message_list():
    query = Message.filter(active=True).order_by("-created_at")
    return await query.all()


@router.post("", response_model=MessageOutSchema)
@public_route()
async def create_message(
    data: MessageEditSchema,
    client_info=Depends(get_client_info),
):
    obj = await Message.create(**data.model_dump(), **client_info)
    return obj


@router.get("/browser_options", response_model=list[BaseSelectOptionSchema])
async def get_message_browser_options():
    return [{"label": item, "value": item, "active": True} for item in BrowserChoice]


@router.delete("/batch_delete")
async def batch_delete_messages(message_ids: list[UUID4]):
    await Message.filter(id__in=message_ids).delete()
    return None


@router.get("/system_options", response_model=list[BaseSelectOptionSchema])
async def get_message_system_options():
    return [{"label": item, "value": item, "active": True} for item in SystemChoice]


@router.put("/{message_id}", response_model=MessageOutSchema)
async def update_message(message_id: UUID4, data: MessageEditSchema):
    obj = await Message.get_or_raise(id=message_id)
    await obj.update_from_dict(data.model_dump(exclude_unset=True))
    await obj.save()
    return obj


@router.delete("/{message_id}")
async def delete_message(message_id: UUID4):
    obj = await Message.get_or_raise(id=message_id)
    await obj.delete()
    return None
